﻿package com.tools
{
	import com.config.GalleryConfig;
	
	import com.main.Gallery;
	
	import flash.events.*;
	// classes requises pour recevoir/envoyer des données vers AMF
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.ObjectEncoding;
	
	public class AMFPHPBusinessDelegate
	{
		private var gateway							: String 			= GalleryConfig.AMFPHP_GATEWAY;
		private var service							: String 			= GalleryConfig.AMFPHP_GALLERY_SERVICE;
		private static const ALL_IMAGES_OPERATION	: String			= "getAllImages";
		private static const RESULT_SUFFIX			: String			= "_result";
		private static const FAULT_SUFFIX			: String			= "_fault";
		private var connection						: NetConnection;
		private var responder						: Responder;
		
		public function AMFPHPBusinessDelegate( )
		{
			// on crée la connection
			connection = new NetConnection;
			// on indique l'emplacement de la passerelle : Gateway.php
			connection.connect(gateway);
			connection.objectEncoding = ObjectEncoding.AMF3;
		}
		
		public function getAllImages ( ) : void
		{
			// on crée un répondeur pour traiter la réponse du serveur
			//responder = new Responder( this[ ALL_IMAGES_OPERATION + RESULT_SUFFIX ], this[ ALL_IMAGES_OPERATION + FAULT_SUFFIX ] );
			responder = new Responder ( getAllImages_result, getAllImages_fault );
			// on lance la requête sur le service en liant le répondeur 
			connection.call( service + "." + ALL_IMAGES_OPERATION, responder );
			connection.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
			trace("l'appel au service est lancé\nservice : " + service +"\noperation : "+ ALL_IMAGES_OPERATION);
		}
		
		private function netStatusHandler ( ev : NetStatusEvent ) : void
		{
			//var gallery : Gallery = Gallery.getInstance( );
			//gallery.afficheNotif( ev.info.code +" "+ ev.info.level );
			trace( "-> "+ ev.info.code +" / "+ ev.info.level );
		}
		
		private function getAllImages_result ( result : Object ) : void
		{
			trace("le service a renvoyé quelque chose...");
			trace(result is Array);
			
			var gallery : Gallery = Gallery.getInstance( );
			gallery.loadGalleryFromInfos( result as Array );
		}
		
		private function getAllImages_fault ( fault : Object ) : void
		{
			var gallery : Gallery = Gallery.getInstance( );
			gallery.afficheNotif( fault.description );
			trace("l'appel au service a échoué");
		}
	}
}